package controller

import (
	"context"
	"fmt"
	"game-server/database"
	"game-server/model"
	"log"
	"net/http"
	pb "proto"
	"time"

	"github.com/gin-gonic/gin"
)

type MatchController struct {
	crossClient pb.CrossServiceClient
}

func NewMatchController(crossClient pb.CrossServiceClient) *MatchController {
	return &MatchController{
		crossClient: crossClient,
	}
}

// 测试调用
func (mc *MatchController) TestRpcMatch(c *gin.Context) {
	// 从token中获取用户ID
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
		return
	}

	// 获取玩家当前布阵
	var formation model.Formation
	result := database.DB.Where("user_id = ?", userID).First(&formation)
	if result.Error != nil {
		return
	}

	// 转换为proto格式
	var protoFormation []*pb.HeroPosition
	for pos, heroID := range formation.Positions {
		if heroID > 0 {
			protoFormation = append(protoFormation, &pb.HeroPosition{
				HeroId:   int32(heroID),
				Position: int32(pos),
			})
		}
	}

	// 设置60秒超时的context
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	// 创建请求
	request := &pb.CrossServerRequest{
		PlayerId:  fmt.Sprintf("%d", userID.(uint)),
		Formation: protoFormation,
	}

	// 调用RPC
	response, err := mc.crossClient.HandleCrossServerRequest(ctx, request)
	if err != nil {
		log.Printf("RPC call failed: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "RPC call failed"})
		return
	}

	if !response.Success {
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"message": response.Message,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    string(response.Data),
	})
}
